<%@ page contentType="text/html; charset=UTF-8"%>
<%@page import="edu.ccut.saturn.component.SaturnData"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<%@ include file="/extjs/include/all.jsp"%>
<script type="text/javascript" src="${pageContext.request.contextPath}/extjs/js/validate.js"></script>
<title></title>
<script type="text/javascript">
Ext.onReady(function(){
	Ext.QuickTips.init();
	var resultWidth = Ext.get("panel").getWidth();
	 var panel = new Ext.FormPanel({
	        labelWidth: 80,
	        title:"添加完全代理",
	        autoWidth:true,
	        border:false,
	        renderTo:"form_area",
	        labelWidth: 60,
	        frame:true,
	        items: [{
	            layout:'column',
	            items:[{
	                columnWidth:.25,
	                layout: 'form',
	                items: [{
	                    xtype:'textfield',
	                    fieldLabel: '委托人',
	                    name: 'agent_from_name',
	                    id: 'agent_from_name',
	                   //allowBlank:false,
		                msgTarget:'qtip',
	                    readOnly:true
	                },{
	                    xtype:'hidden',
	                    name: 'agent_from',
	                    id: 'agent_from'
	                }]
	            },{
	                columnWidth:.25,
	                layout: 'form',
	                items: [{
	                    xtype:'button',
	                    text: '选择委托人',
	                    handler:chooseDelegate
		            }]
	            },{
	                columnWidth:.25,
	                layout: 'form',
	                items: [{
		                    xtype:'textfield',
		                    fieldLabel: '代理人',
		                    name: 'agent_name',
		                    id: 'agent_name',
		                    //allowBlank:false,
		                    msgTarget:'qtip',
		                    readOnly:true
		                },{
			                 name:'agent_to_type',
			                 id:'agent_to_type',
				        	 xtype:'hidden'
					      },{
		                    xtype:'hidden',
		                    name: 'agent_to',
		                    id: 'agent_to'
	                }]
	               },{
		                columnWidth:.25,
		                layout: 'form',
		                items: [{
	                    xtype:'button',
	                    text: '选择代理人',
	                    handler:chooseAgent
	                }]
	            },{
	                columnWidth:.5,
	                layout: 'form',
	                items: [{
			        	xtype:'datefield',
			        	id:'start_time',
			        	name:'start_time',
			        	fieldLabel:'开始时间',
			        	readOnly:true,
			            allowBlank:false,
		                msgTarget:'qtip',
			        	anchor:'50%'
			        },{
			        	xtype:'datefield',
			        	id:'end_time',
			        	name:'end_time',
			        	fieldLabel:'终止时间',
			        	readOnly:true,
			        	allowBlank:false,
		                msgTarget:'qtip',
			        	anchor:'50%'
			        }]
	            },{ 
	                columnWidth:.5,
	                layout: 'form',
	                items: [{
		                 width:150,
		                 name:'agent_reason',
		                 id:'agent_reason',
			        	 xtype:'textarea',
			        	 fieldLabel:'代理原因',
			        	 maxLength:20,
			        	 vtype:'isNumberAlphaUnderlineChinese',
			        	 allowBlank:false,
		                 msgTarget:'qtip',
			        	 anchor:'60%'
				    }] 
				}] 
        }]
			
		});
		
		function chooseDelegate(){
			var root=new Ext.tree.AsyncTreeNode({
				id:"root_participant",
				text:"参与者"});
			var tree=new Ext.tree.TreePanel({
				root:root,
				loader: new Ext.tree.TreeLoader({url:'${pageContext.request.contextPath}/edu.ccut.saturn.workflow.client::/agentModule/action/GetTreeJson.action'}),
				width:400,
				autoScroll: true
			});	

		  tree.on('click', function(node){
					addAgentFrom(node.id,node.text);
				},this);
	       var window = new Ext.Window({
				title: '添加委托人',
				width: 500,
				height:300,
				minWidth: 300,
				minHeight: 200,
				layout: 'fit',
				plain:true,
				items:tree,
				buttonAlign:'center',
				modal:true
			});
			window.show();
		};
		
		function chooseAgent(){
			var root=new Ext.tree.AsyncTreeNode({
				id:"root_participant",
				text:"参与者"});
			var tree=new Ext.tree.TreePanel({
				root:root,
				loader: new Ext.tree.TreeLoader({url:'${pageContext.request.contextPath}/edu.ccut.saturn.workflow.client::/agentModule/action/GetTreeJson.action'}),
				width:400,
				autoScroll: true
			});	

		  tree.on('click', function(node){
					addAgentTo(node.id,node.text);
				},this);
	       var window = new Ext.Window({
				title: '添加代理人',
				width: 500,
				height:300,
				minWidth: 300,
				minHeight: 200,
				layout: 'fit',
				plain:true,
				items:tree,
				buttonAlign:'center',
				modal:true
			});
			window.show();
		};
			
	   var fields = [
		   {name: 'process_define_id', mapping : 'process_define_id'},
		   {name: 'process_xml_key', mapping : 'process_xml_key'}];
		   
		var firstGridStore = new Ext.data.JsonStore({
		    url: '${pageContext.request.contextPath}/edu.ccut.saturn.workflow.client::/agentModule/action/QueryProcess.action',
		    root: 'result',
		    fields: fields
		});
	
		var cols = [
				{ id : 'process_define_id', header: "流程定义ID", width: resultWidth*0.1, sortable: true, dataIndex: 'process_define_id'},
				{header: "流程名称", width: resultWidth*0.4, sortable: true, dataIndex: 'process_xml_key'}];

	   var firstGrid = new Ext.grid.GridPanel({
			ddGroup : 'secondGridDDGroup',
	        store : firstGridStore,
	        columns : cols,
			enableDragDrop: true,
	        stripeRows : true,
	        width : resultWidth*0.5,
			region : 'west',
	        title : '可选择的例外流程'
	    });

		firstGridStore.load();
		
		var secondGridStore = new Ext.data.JsonStore({
		        fields : fields,
				root   : 'result'
		    });

		var secondGrid = new Ext.grid.GridPanel({
			ddGroup: 'firstGridDDGroup',
	        store: secondGridStore,
	        columns: cols,
			enableDragDrop: true,
	        stripeRows: true,
	        width: resultWidth*0.5,
			region: 'center',
	        title: '已选择的例外流程'
	    });
		
		var displayPanel = new Ext.Panel({
			autoWidth:true,
			height   : 300,
			title:"选择例外流程",
			layout   : 'border',
			renderTo : 'panel',
			items    : [
				firstGrid,
				secondGrid
			],
			bbar: [
				'->',
				{
					text    : '确认',
					handler : function() {
					  var excpProcessIds = "";
					  if(secondGridStore.getCount()>0){
					     for (var i = 0; i < secondGridStore.getCount(); i++) {
					        var rec = secondGridStore.getAt(i);
					        excpProcessIds += rec.get("process_define_id")+",";
					      }			        
					   }
					   excpProcessIds = excpProcessIds.substring(0,excpProcessIds.length-1);
					        var agent_from = Ext.get("agent_from").dom.value;
					        var agent_to = Ext.get("agent_to").dom.value;
				  		    var agent_to_type = Ext.get("agent_to_type").dom.value;
				  		    var start_time = new Date(Ext.get("start_time").dom.value);
				  		    var end_time = new Date(Ext.get("end_time").dom.value);
				  		    var agent_reason = Ext.get("agent_reason").dom.value;
				  		    var agent_from_name = Ext.get("agent_from_name").dom.value;
				  		    var agent_name = Ext.get("agent_name").dom.value;
				  		    
				  		    if(agent_from_name==''){
				  		    	Ext.Msg.alert('信息',"请选择委托人"); 
				  		    }else if(agent_name==''){
				  		    	Ext.Msg.alert('信息',"请选择代理人"); 
				  		    }else if(agent_from!=''&&agent_to!=''&&agent_from==agent_to&&agent_to_type=="user"){
				  		    	 Ext.Msg.alert('信息',"代理人不能和委托人相同"); 
				  		    }else if(start_time>=end_time){
			  		    		 Ext.Msg.alert('信息',"终止时间应大于开始时间"); 
			  		    	}else if(panel.form.isValid()){
					  			Ext.Ajax.request({
								     method : 'POST',                           
								     url: '${pageContext.request.contextPath}/edu.ccut.saturn.workflow.client::/agentModule/action/SetAllAgent.action',     
								     success:function(request){    
									       var myResult = Ext.util.JSON.decode(request.responseText);
									       Ext.Msg.alert('信息',myResult.message,function(){
									      	  window.location="agentList.jsp"; 
									       });       
								     },
								     failure:function(){                          
								         Ext.Msg.alert("错误", "与后台联系的时候出现了问题");
								     },
								     params:{
								     		agent_to:agent_to, 
								     		agent_to_type:agent_to_type, 
								     		start_time:start_time.format('Y-m-d H:i:s'), 
								     		end_time:end_time.format('Y-m-d H:i:s'), 
								     		excpProcessIds:excpProcessIds, 
								     		agent_from:agent_from,
								     		agent_reason:agent_reason
								     } 
						     	});
						     }
					}
				},
				{
					text : '重置',
					handler : function() {
						firstGridStore.load();
						secondGridStore.removeAll();
						panel.getForm().reset();
					}
				},
				{
					text : '返回',
					handler : function() {
						window.history.back();
					}
				}
			]
		});
		
		var blankRecord =  Ext.data.Record.create(fields);
		
		var firstGridDropTargetEl =  firstGrid.getView().el.dom.childNodes[0].childNodes[1];
		var firstGridDropTarget = new Ext.dd.DropTarget(firstGridDropTargetEl, {
			ddGroup    : 'firstGridDDGroup',
			copy       : true,
			notifyDrop : function(ddSource, e, data){
				function addRow(record, index, allItems) {
					
					var foundItem = firstGridStore.find('process_define_id', record.data.process_define_id);
					if (foundItem  == -1) {
						firstGridStore.add(record);
						firstGridStore.sort('process_define_id', 'ASC');
						ddSource.grid.store.remove(record);
					}
				}
				Ext.each(ddSource.dragData.selections ,addRow);
				return(true);
			}
		}); 	
		
		var secondGridDropTargetEl = secondGrid.getView().el.dom.childNodes[0].childNodes[1]
	
		var destGridDropTarget = new Ext.dd.DropTarget(secondGridDropTargetEl, {
			ddGroup    : 'secondGridDDGroup',
			copy       : false,
			notifyDrop : function(ddSource, e, data){
				function addRow(record, index, allItems) {
					var foundItem = secondGridStore.find('process_define_id', record.data.process_define_id);
					if (foundItem  == -1) {
						secondGridStore.add(record);
						secondGridStore.sort('process_define_id', 'ASC');
						ddSource.grid.store.remove(record);
					}
				}
				Ext.each(ddSource.dragData.selections ,addRow);
				return(true);
			}
		}); 
		
		function addAgentFrom(userid,name){
			if(userid=='root_participant'){
				return false;
			}
			if(userid!='rootDept'&& userid!='rootRole'){
			 	var type = userid.split('_')[0];
			 	var id = userid.split('_')[1];
			 	if(type=='deptUser'||type=='roleUser'){
			 		Ext.get("agent_from").dom.value =id;
			 		Ext.get("agent_from_name").dom.value =name;
			 	}
		   }
		}
	function addAgentTo(userid,name){
		 if(userid=='root_participant'){
			return false;
		 }
		 if(userid!='rootDept'&& userid!='rootRole'){
		 	var type = userid.split('_')[0];
		 	var id = userid.split('_')[1];
		 	if(type=='deptUser'||type=='roleUser'){
		 		Ext.get("agent_to_type").dom.value ="user";
		 		Ext.get("agent_to").dom.value =id;
		 		Ext.get("agent_name").dom.value =name;
		 	}
		 	else if(type=='dept'){
		 		Ext.get("agent_to_type").dom.value ="dept";	
		 		Ext.get("agent_to").dom.value =id;
		 		Ext.get("agent_name").dom.value =name; 		
		 	}
		 	else if(type=='role'){
		 		Ext.get("agent_to_type").dom.value ="role";
		 		Ext.get("agent_to").dom.value =id;
		 		Ext.get("agent_name").dom.value =name;
		 	}
		 }
	 }
});
</script>
</head>
<div id="form_area"></div>
<div id="panel" width="100%"></div>
</html>